package com.knife.news.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.knife.news.object.Link;
import com.knife.news.object.News;
import com.knife.news.object.Pages;
import com.knife.util.CommUtil;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

public class TypeAction extends BaseCmdAction {

	public Page doInit(WebForm form, Module module) {
		//sid传值说明是分类树中的分类
		if(!"0".equals(sid)){
			thisType.setSite(sid);
		}
		if(treenews!=null){
			if(!"0".equals(treenews)){
				thisType.setTreenews(treenews);
			}
		}
		String tmpUrl="";
		if(thisType!=null){
			tmpUrl=CommUtil.null2String(thisType.getUrl());
		}
		if(tmpUrl.length()>0){
			return new Page("typeIndex",thisType.getUrl(),"url");
		}else{
			if(thisType!=null){
				//是否需要会员浏览
				if(thisType.getIsmember()>0){
					if(loginUser==null){
						return new Page("userLogin","/user.do?parameter=login&tid="+tid,"url");
					}
				}
				if(thisType.getShow()==1){
					return doShow(form,module);
				}else{
					String useTemplate="";
					if(null!=thisType.getIndex_template()){
						useTemplate=thisType.getIndex_template();
					}
					if(useTemplate.length()>0){
						return doIndex(form,module);
					}else{
						return doList(form,module);
					}
				}
			}else{
				return new Page("Error","/sys/no-type.htm");
			}
		}
	}
	
	public Page doShow(WebForm form, Module module){
		String ext="";
		try{
			ext = thisType.getNews_template().substring(thisType.getNews_template().lastIndexOf(".")+1);
		}catch(Exception e){}
		if(!ext.equalsIgnoreCase("url") && !ext.equalsIgnoreCase("json")&& !ext.equalsIgnoreCase("xml")){
			ext="html";
		}
		return new Page("typeNews", thisType.getNews_template(),ext,"/web/" + thisSite.getTemplate() + "/");
	}
	
	public Page doPreview(WebForm form, Module module){
		if(thisType==null){
			return new Page("Error","/sys/no-type.htm");
		}
		String path="";
		if(thisType.getShow()==1){
			path=thisSite.getTemplate() + "/"+thisType.getNews_template();
		}else{
			path=thisSite.getTemplate() + "/"+thisType.getType_template();
		}
		File realTemplate=new File(Globals.APP_BASE_DIR + "WEB-INF/templates/web/" + path);
		File tempTemplate=new File(Globals.APP_BASE_DIR + "WEB-INF/templates/tmp/" + path);
		if(!tempTemplate.getParentFile().exists()){
			tempTemplate.getParentFile().mkdirs();
		}
		String content="";
		try {
			File[] incfiles = (new File(Globals.APP_BASE_DIR + "WEB-INF/templates/web/" + thisSite.getTemplate() + "/inc/")).listFiles();
			if(incfiles!=null){
			for (int i = 0; i < incfiles.length; i++) {
				File realincfile=incfiles[i];
				if (realincfile.isFile()) {
					File newincfile= new File(realincfile.getAbsolutePath().replace(File.separator+"web"+File.separator, File.separator+"tmp"+File.separator));
					if(!newincfile.getParentFile().exists()){
						newincfile.getParentFile().mkdirs();
					}
					if(!newincfile.exists()){
						newincfile.createNewFile();
					}
					if(newincfile.canWrite()){
						content = org.apache.commons.io.FileUtils.readFileToString(realincfile, "UTF-8");
						if(thisSite.getHtml()==1){
							content = content.replace("\"/skin/", "\"/html/"+thisSite.getPub_dir()+"/skin/");
							content = content.replace("'/skin/", "'/html/"+thisSite.getPub_dir()+"/skin/");
						}
						org.apache.commons.io.FileUtils.writeStringToFile(newincfile,content,"UTF-8");
					}
				}
			}
			}
			if(!tempTemplate.exists()){
				tempTemplate.createNewFile();
			}
			if(tempTemplate.canWrite()){
				content = org.apache.commons.io.FileUtils.readFileToString(realTemplate, "UTF-8");
				if(thisSite.getHtml()==1){
					content = content.replace("\"/skin/", "\"/html/"+thisSite.getPub_dir()+"/skin/");
					content = content.replace("'/skin/", "'/html/"+thisSite.getPub_dir()+"/skin/");
				}
				org.apache.commons.io.FileUtils.writeStringToFile(tempTemplate,content,"UTF-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
			return new Page("Error","/sys/no.htm");
		}
		if(thisType.getShow()==1){
			List<News> topnews = newsDAO.getTopNews(thisType.getId(), 1);
			if (topnews != null) {
				if (topnews.size() > 0) {
					thisNews = (News) topnews.get(0);
					form.addResult("thisNews", thisNews);
				}
			}
			return new Page("typeNews", thisType.getNews_template(),"html","/tmp/" + thisSite.getTemplate() + "/");
		}else{
			String treenews=CommUtil.null2String(form.get("treenews"));
			Collection<Object> paras = new ArrayList<Object>();
			paras.add(thisType.getId());
			String sql="k_display='1' and k_ispub='1' and k_type=?";
			if(treenews.length()>0){
				paras.add(treenews);
				sql+=" and k_treenews=?";
				form.addResult("treenews", treenews);
			}
			int rows = newsDAO.getSum(1, "",thisSite.getId(), thisType.getId(), treenews, "","");
			//System.out.println("取得的文章总数是:"+rows);
			int pageSize = CommUtil.null2Int(thisType.getPagenum());// 每页20条
			int currentPage = 1;
			int totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));// 计算页数
			String orderby=" order by length(k_order) desc,k_order desc";
			if(thisType.getOrderby()!=null){
			switch(thisType.getOrderby()){
				case "pubdatedesc":
					orderby=" order by k_date desc";
					break;
				case "pubdate":
					orderby=" order by k_date";
					break;
				case "titledesc":
					orderby=" order by k_title desc";
					break;
				case "title":
					orderby=" order by k_title";
					break;
				default:
					orderby=" order by length(k_order) desc,k_order desc";
			}
			}
			
			List<News> firstNews = newsDAO.getNewsBySql(sql + orderby, paras, 0, pageSize);
			if(firstNews==null){ firstNews = new ArrayList<News>();}
			List<Link> alllinks=new ArrayList<Link>();
			for(int i=0;i<totalPage;i++){
				Link alink=new Link((i+1)+"",thisType.getHref(i+1));
				alllinks.add(alink);
			}
			int pagesize=10;
			if(thisType.getPagesize()>0){
				pagesize=thisType.getPagesize();
			}
			Pages listPage=new Pages(alllinks,currentPage,pagesize);
			form.addResult("newsList", firstNews);
			form.addResult("listPage", listPage);
			return new Page("typeIndex", thisType.getType_template(),"html","/tmp/" + thisSite.getTemplate() + "/");
		}
	}
	
	public Page doIndex(WebForm form, Module module){
		String useTemplate=thisType.getIndex_template();
		if(useTemplate.length()==0){
			return doList(form,module);
		}
		if(useTemplate.indexOf(",")>0){
			String[] typeTemplates=useTemplate.split(",");
			int showType = CommUtil.null2Int(form.get("st"));
			useTemplate=typeTemplates[showType];
		}
		String ext="";
		try{
			ext = useTemplate.substring(useTemplate.lastIndexOf(".")+1);
		}catch(Exception e){}
		if(!ext.equalsIgnoreCase("url") && !ext.equalsIgnoreCase("json")&& !ext.equalsIgnoreCase("xml")){
			ext="html";
		}
		return new Page("typeIndex", useTemplate,ext,"/web/" + thisSite.getTemplate() + "/");
	}
	
	public Page doList(WebForm form, Module module){
		String useTemplate="list.htm";
		if(thisType!=null){
			if(thisType.getType_template()!=null){
				useTemplate=thisType.getType_template();
			}
		}
		if(useTemplate.length()==0){
			return doIndex(form,module);
		}
		if(useTemplate.indexOf(",")>0){
			String[] typeTemplates=useTemplate.split(",");
			int showType = CommUtil.null2Int(form.get("st"));
			useTemplate=typeTemplates[showType];
		}
		int currentPage = CommUtil.null2Int(form.get("page"));
		if(currentPage>0){
			return doPage(form, module);
		}else{
			currentPage = 1;
		}
		String treenews=CommUtil.null2String(form.get("treenews"));
		Collection<Object> paras = new ArrayList<Object>();
		paras.add(thisType.getId());
		String sql="k_display='1' and k_ispub='1' and k_type=?";
		if(treenews.length()>0){
			paras.add(treenews);
			sql+=" and k_treenews=?";
			form.addResult("treenews", treenews);
		}
		int rows = newsDAO.getSum(1, "",thisSite.getId(), thisType.getId(), treenews, "","");
		//System.out.println("取得的文章总数是:"+rows);
		int pageSize = CommUtil.null2Int(thisType.getPagenum());// 每页20条
		
		int frontPage = 1;
		int nextPage = 2; 
		int totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));// 计算页数
		if(totalPage<1)totalPage=1;
		if(nextPage>totalPage){
			nextPage=totalPage;
		}
		String orderby=" order by length(k_order) desc,k_order desc";
		if(thisType.getOrderby()!=null){
		switch(thisType.getOrderby()){
			case "pubdatedesc":
				orderby=" order by k_date desc";
				break;
			case "pubdate":
				orderby=" order by k_date";
				break;
			case "titledesc":
				orderby=" order by k_title desc";
				break;
			case "title":
				orderby=" order by k_title";
				break;
			default:
				orderby=" order by length(k_order) desc,k_order desc";
		}
		}
		List<News> firstNews = newsDAO.getNewsBySql(sql + orderby, paras, 0, pageSize);
		if(firstNews==null){ firstNews = new ArrayList<News>();}
		List<Link> alllinks=new ArrayList<Link>();
		for(int i=0;i<totalPage;i++){
			Link alink=new Link((i+1)+"",thisType.getHref(i+1));
			alllinks.add(alink);
		}
		int pagesize=10;
		if(thisType.getPagesize()>0){
			pagesize=thisType.getPagesize();
		}
		Pages listPage=new Pages(alllinks,currentPage,pagesize);
		form.addResult("rows", rows);
		form.addResult("pageSize", pageSize);
		form.addResult("frontPage", frontPage);
		form.addResult("currentPage", currentPage);
		form.addResult("nextPage", nextPage);
		form.addResult("totalPage", totalPage);
		form.addResult("newsList", firstNews);
		form.addResult("listPage", listPage);
		String ext="";
		try{
			ext = useTemplate.substring(useTemplate.lastIndexOf(".")+1);
		}catch(Exception e){}
		if(!ext.equalsIgnoreCase("url") && !ext.equalsIgnoreCase("json")&& !ext.equalsIgnoreCase("xml")){
			ext="html";
		}
		return new Page("typeIndex", useTemplate,ext,"/web/" + thisSite.getTemplate() + "/");
	}

	public Page doPage(WebForm form, Module module) {
		String useTemplate="list.htm";
		if(thisType!=null){
			if(thisType.getType_template()!=null){
				useTemplate=thisType.getType_template();
			}
		}
		if(useTemplate.length()==0){
			return doIndex(form,module);
		}
		if(useTemplate.indexOf(",")>0){
			String[] typeTemplates=useTemplate.split(",");
			int showType = CommUtil.null2Int(form.get("st"));
			useTemplate=typeTemplates[showType];
		}
		String treenews=CommUtil.null2String(form.get("treenews"));
		Collection<Object> paras = new ArrayList<Object>();
		paras.add(thisType.getId());
		String sql="k_display='1' and k_ispub='1' and k_type=?";
		if(treenews.length()>0){
			paras.add(treenews);
			sql+=" and k_treenews=?";
			form.addResult("treenews", treenews);
		}
		int rows = newsDAO.getSum(1, "",thisSite.getId(), thisType.getId(), treenews, "","");
		int pageSize = CommUtil.null2Int(thisType.getPagenum());
		int currentPage = CommUtil.null2Int(form.get("page"));
		int totalPage = (int) Math.ceil((float) rows / (float) pageSize);
		if(currentPage<1){currentPage=1;}
		if(currentPage>totalPage){currentPage=totalPage;}
		int frontPage = currentPage - 1;
		int nextPage = currentPage + 1;
		int begin = (currentPage - 1) * pageSize + 1;
		int end = rows - begin + 1;
		if(end<0){end=0;}
		List<News> newsList = new ArrayList<News>();
		String orderby=" order by length(k_order) desc,k_order desc";
		if(thisType.getOrderby()!=null){
		switch(thisType.getOrderby()){
			case "pubdatedesc":
				orderby=" order by k_date desc";
				break;
			case "pubdate":
				orderby=" order by k_date";
				break;
			case "titledesc":
				orderby=" order by k_title desc";
				break;
			case "title":
				orderby=" order by k_title";
				break;
			default:
				orderby=" order by length(k_order) desc,k_order desc";
		}
		}
		if (end < pageSize) {
			newsList = newsDAO.getNewsBySql(sql+orderby, paras, begin - 1, end);
		} else {
			newsList = newsDAO.getNewsBySql(sql+orderby, paras, begin - 1, pageSize);
		}
		form.addResult("currentPage", currentPage);
		form.addResult("totalPage", totalPage);
		form.addResult("pageSize", pageSize);
		form.addResult("frontPage", frontPage);
		form.addResult("nextPage", nextPage);
		form.addResult("rows", rows);
		form.addResult("newsList", newsList);
		List<Link> alllinks=new ArrayList<Link>();
		for(int i=0;i<totalPage;i++){
			Link alink=new Link((i+1)+"",thisType.getHref(i+1));
			alllinks.add(alink);
		}
		int pagesize=10;
		if(thisType.getPagesize()>0){
			pagesize=thisType.getPagesize();
		}
		Pages listPage=new Pages(alllinks,currentPage,pagesize);
		form.addResult("listPage", listPage);
		String ext="";
		try{
			ext = useTemplate.substring(useTemplate.lastIndexOf(".")+1);
		}catch(Exception e){
		}
		if(!ext.equalsIgnoreCase("url") && !ext.equalsIgnoreCase("json")&& !ext.equalsIgnoreCase("xml")){
			ext="html";
		}
		return new Page("typeIndex", useTemplate,ext,"/web/" + thisSite.getTemplate() + "/");
	}

	public Page doShowType(WebForm form, Module module) {
		String type = (String) form.get("type");
		List<News> newsList = newsDAO.getNewsBySql("k_type=" + type, null, 0, 30);
		form.addResult("newsList", newsList);
		List<com.knife.news.object.Type> typeList = typeDAO.getTypesBySql("k_type='1'");
		form.addResult("typeList", typeList);
		return module.findPage("index");
	}
	
	public Page doProductList(WebForm form, Module module){
		return new Page("typeIndex", thisType.getType_template(),"/web/" + thisSite.getTemplate() + "/");
	}
}
